import {
    setTagNavListInLocalstorage,
    getTagNavListFromLocalstorage,
    getBreadCrumbList,
    routeHasExist
} from '@/libs/menus'
import { setToken } from "@/libs/auth";
import { setStore } from '@/libs'

const USER = 'user',
      ROLES = 'roles',
      IS_ADMIN = 'is_admin',
      ACCESS = 'access';

export default {
    /**
     * ///////////////////////////////////////////////////////////////
     * 侧边栏、面包屑、导航相关
     * ///////////////////////////////////////////////////////////////
     */
    /**
     * 侧边栏收起或展开
     */
    toggleCollapseSidebar: state => {
        state.collapseSidebar = !state.collapseSidebar
    },

    /**
     * 面包屑导航
     * @param {*} state
     * @param {*} routeMetched
     */
    setBreadCrumb(state, routeMetched) {
        state.breadCrumbList = getBreadCrumbList(routeMetched, state.breadCrumbHomeRoute)
    },

    /**
     * 导航标签保存
     * @param {*} state
     * @param {*} list
     */
    setTagNavList: (state, list) => {
        if (list) {
            let isHideInTags = list[list.length - 1].meta.hideInTags
            if (!isHideInTags) {
                state.tagNavList = [...list]
                setTagNavListInLocalstorage([...list])
            }
        } else {
            state.tagNavList = getTagNavListFromLocalstorage()
        }
    },
    addTag(state, { route, type = 'unshift' }) {
        if (!routeHasExist(state.tagNavList, route)) {
            if (type === 'push') state.tagNavList.push(route)
            else {
                if (route.name === 'console') state.tagNavList.unshift(route)
                else state.tagNavList.splice(1, 0, route)
            }
            setTagNavListInLocalstorage([...state.tagNavList])
        }
    },


    /**
     * ///////////////////////////////////////////////////////////////
     * 用户登录状态相关
     * ///////////////////////////////////////////////////////////////
     */
    SET_TOKEN: (state, token) => {
        state.token = token
        setToken(token)
    },
    SET_USER: (state, data) => {
        state.user = data
        setStore({ name: USER, content: data, type: 'session' })
    },
    SET_IS_ADMIN: (state, data) => {
        state.isAdmin = (data ? (data == 1 ? true : false) : false)
        setStore({ name: IS_ADMIN, content: state.isAdmin, type: 'session' })
    },
    SET_ROLES: (state, data) => {
        state.roles = (data == undefined ? [] : data)
        setStore({ name: ROLES, content: data, type: 'session' })
    },
    SET_ACCESS(state, access) {
        state.access = (access == undefined ? [] : access)
        setStore({ name: ACCESS, content: access, type: 'session' })
    },
}
